﻿    dojo.require("dijit.form.Button");
    dojo.require("dijit.TitlePane");
    dojo.require("dijit.form.TextBox");
    dojo.require("dijit.layout.ContentPane");
    dojo.require("dijit.layout.BorderContainer");
    dojo.require("sangobang.playerPanelItem");
    dojo.registerModulePath("sangobang", "../sangobang");
    game = {playerList: []
    };
    function OnJoinClick()
    {
        var yourname = document.getElementById("DisplayName");
        if (yourname.value == "")
        {
            alert("Please input your name first");
            return ;
        }
        game.player = { name: yourname.value };                
        MessageController.OnRecvMsg = OnRequestCompleteGet;
        MessageController.Join("<message type=\"newuser\"><user>"+yourname.value +"</user></message>");
    }
    function OnRequestCompleteGet(result)
    {
        var xmldoc = XML.parse(result);
        var msg = xmldoc.getElementsByTagName("message")[0];
        var type = msg.getAttribute("type");
        var func = messageHandler[type];
        if (func) {
            func(msg);
        }
    }
    var messageHandler = {
        joinResult : joinResultHandler,
        playerList: playerListHandler
    };
    function joinResultHandler(msg){
        var result = msg.getAttribute("result");
        if (result == "success"){
            dijit.byId("LeaveButton").setAttribute("disabled", false);
            dijit.byId("JoinButton").setAttribute("disabled", true);
            var guid = msg.getElementsByTagName("guid")[0];
            MessageController.guid = guid.firstChild.nodeValue;
            
            Service.GetMsg(MessageController.guid, MessageController._OnGetMsgComplete);
        }
        else{
            alert(args);
        }
    }
    function playerListHandler(msg) {
        var players = msg.childNodes;
        var i = 0;
        var playersPanel = $("#playersPanel");
        for (;i<players.length;++i){
            var player = players[i];
            playersPanel.append("<div id='player" + i + "' class='playerItem'>" + player.firstChild.nodeValue + "</div>");
            var playerPanelItem = new sangobang.playerPanelItem({ title: player.firstChild.nodeValue, src: "" }, dojo.byId("player" + i));
        }
    }


    dojo.addOnLoad(function() {
        var joinButton = dojo.byId("JoinButton");
        dojo.connect(joinButton, "onclick", OnJoinClick)

    }); 
